package com.lhy.wcss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhy.wcss.common.BaseConstant;
import com.lhy.wcss.common.utls.ExcelUtil;
import com.lhy.wcss.model.domain.Knrd;
import com.lhy.wcss.model.domain.UserManage;
import com.lhy.wcss.model.domain.WhitelistSetting;
import com.lhy.wcss.mapper.WhitelistSettingMapper;
import com.lhy.wcss.model.dto.PageDTO;
import com.lhy.wcss.model.dto.StatDTO;
import com.lhy.wcss.model.vo.WhitelistSettingVO;
import com.lhy.wcss.service.KnrdService;
import com.lhy.wcss.service.UserManageService;
import com.lhy.wcss.service.WhitelistSettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

//学校用户白名单设置 服务实现类

@Service
public class WhitelistSettingServiceImpl extends ServiceImpl<WhitelistSettingMapper, WhitelistSetting> implements WhitelistSettingService {
    @Autowired
    private KnrdService knrdService;
    @Autowired
    private UserManageService userManageService;
    /*登录*/
    @Override
    public WhitelistSetting login(WhitelistSetting whitelistSetting) {
        QueryWrapper<WhitelistSetting> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(WhitelistSetting::getSn,whitelistSetting.getSn())
                .eq(WhitelistSetting::getPassword,whitelistSetting.getPassword())
                .eq(WhitelistSetting::getEnabled,Boolean.TRUE);
        WhitelistSetting one = this.getOne(wrapper);
        return one;

    }
    /*获取白名单所有数据，分页 */
    @Override
    public Page<WhitelistSettingVO> getPage(PageDTO pageDTO, WhitelistSetting whitelistSetting) {
        //LambdaQueryWrapper<WhitelistSetting> wrapper=new LambdaQueryWrapper<>();
        /*分页器*/
        Page<WhitelistSettingVO> page=new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
//        if(StringUtils.isNotBlank(whitelistSetting.getSn())){
//            wrapper.like(WhitelistSetting::getSn,whitelistSetting.getSn()).or().like(WhitelistSetting::getSn,whitelistSetting.getName());
//        }
//        if(Objects.nonNull(whitelistSetting.getRoleId())){
//            wrapper.eq(WhitelistSetting::getRoleId,whitelistSetting.getRoleId());
//        }
//        if(Objects.nonNull(whitelistSetting.getEnabled())){
//            wrapper.eq(WhitelistSetting::getEnabled,whitelistSetting.getEnabled());
//        }
//        this.page(page,wrapper);
        baseMapper.page(page, whitelistSetting);
        return page;
    }

    @Override
    public WhitelistSetting getBySn(String sn) {
        WhitelistSetting whitelistSetting=new WhitelistSetting();
        /*LambdaQueryWrapper<WhitelistSetting> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(WhitelistSetting::getSn,sn);
        whitelistSetting = this.getOne(wrapper);
        if(Objects.isNull(whitelistSetting)){
            whitelistSetting=new WhitelistSetting();*/
            LambdaQueryWrapper<UserManage> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(UserManage::getUserSn,sn).groupBy(UserManage::getUserSn);
            UserManage userManage = userManageService.getOne(wrapper1);
            if(Objects.nonNull(userManage)){
                whitelistSetting.setName(userManage.getUserName());
                whitelistSetting.setSn(userManage.getUserSn());
                whitelistSetting.setRoleId(userManage.getRoleId());
                return whitelistSetting;
            }
            LambdaQueryWrapper<Knrd> wrapper2=new LambdaQueryWrapper<>();
            wrapper2.eq(Knrd::getStudentId,sn).groupBy(Knrd::getStudentId);
            Knrd knrd = knrdService.getOne(wrapper2);
            System.out.println(knrd);
            if(Objects.nonNull(knrd)){
                whitelistSetting.setName(knrd.getName());
                whitelistSetting.setSn(knrd.getStudentId());
                whitelistSetting.setRoleId(BaseConstant.STUDENT_ID);
                return whitelistSetting;
            }
//        }
            return null;
    }

    @Override
    public boolean saveBySelf(WhitelistSetting whitelistSetting) {
        LambdaQueryWrapper<WhitelistSetting> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(WhitelistSetting::getSn,whitelistSetting.getSn());
        WhitelistSetting one = this.getOne(wrapper);
        if(Objects.isNull(one)){
            boolean save = this.save(whitelistSetting);
            return save;
        }
        return false;

    }

    @Override
    public void export(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment; filename=whiteList.xls");
        PageDTO pageDTO=new PageDTO().setPageSize(-1);
        WhitelistSetting whitelistSetting = new WhitelistSetting();

        Page<WhitelistSettingVO> page = getPage(pageDTO, whitelistSetting);

        /*创建excel表格对象*/
        /*Workbook sheets = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = sheets.createSheet();
        // 创建row
        Row row = sheet.createRow(0);
        // 创建ROW
        Cell cell = row.createCell(0);
        // 设置value
        cell.setCellValue("学工号");

        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("角色");
        cell = row.createCell(3);
        cell.setCellValue("启用状态");

        for(int i=0;i<page.getRecords().size();i++){
            row=sheet.createRow(i+1);
            cell=row.createCell(0);
            cell.setCellValue(page.getRecords().get(i).getSn());
            cell=row.createCell(1);
            cell.setCellValue(page.getRecords().get(i).getName());
            cell=row.createCell(2);
            cell.setCellValue(page.getRecords().get(i).getRoleName());
            cell=row.createCell(3);
            cell.setCellValue(page.getRecords().get(i).getEnabled()?"启用":"禁用");
        }

        // 将对象转为流添加到响应中
        try {
            sheets.write(response.getOutputStream());
        } catch (IOException e) {

        }*/

        try {
            ExcelUtil.exportUser(response,page.getRecords());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void exportTemp(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment; filename=whiteListTemp.xls");
        try {
            ExcelUtil.exportUserTemp(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String,Object> inputUser(MultipartFile file) {
        Map<String, Object> msg = new HashMap<>();
        //检查文件是否为Excel
        String s1 = ExcelUtil.checkFile(file);
        if (StringUtils.isNotBlank(s1)) {
            msg.put("error", s1);
            return msg;
        }
        // 验证文件内容--表头验证（是否符合要求）
        List<String[]> strings = null;
        try {
            strings = ExcelUtil.readExcel(file);
            String notBlank = ExcelUtil.checkHead(strings.get(0));
            if (StringUtils.isNotBlank(notBlank)) {
                msg.put("error", notBlank);
                return msg;
            }

            List<WhitelistSetting> users = new ArrayList<>();
            List<WhitelistSetting> existUsers = new ArrayList<>();
            Map<String, Long> map = new HashMap<>();
            for (int i=1;i<strings.size();i++) {
                QueryWrapper<WhitelistSetting> wrapper=new QueryWrapper<>();
                wrapper.lambda().eq(WhitelistSetting::getSn,strings.get(i)[0]);
                WhitelistSetting one = this.getOne(wrapper);
                if(Objects.isNull(one)){
                    WhitelistSetting whitelistSetting = new WhitelistSetting()
                            .setSn(strings.get(i)[0])
                            .setName(strings.get(i)[1])
                            .setPassword(strings.get(i)[0])
                            .setRoleId(BaseConstant.ROLE_MAP.get(strings.get(i)[2]))
                            .setEnabled(BaseConstant.ENABLE_MAP.get(strings.get(i)[3]));
                    users.add(whitelistSetting);
                }else{
                    existUsers.add(one);
                }
            }
            if(existUsers.size()==0){
                this.saveBatch(users);
                msg.put("success", "成功导入白名单用户" + users.size() + "人");
                return msg;
            }
            msg.put("error","部分数据重复请重新验证，重复数据如下"+gets(existUsers));
            return msg;
        } catch (IOException e) {
            e.printStackTrace();
            msg.put("error","内部程序错误！");
            return msg;
        }


    }

    @Override
    public Page<WhitelistSetting> pageList(PageDTO pageDTO, WhitelistSetting whitelistSetting) {
        QueryWrapper<WhitelistSetting> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(whitelistSetting.getSn())){
            wrapper.like("sn",whitelistSetting.getSn());
        }
        if(StringUtils.isNotBlank(whitelistSetting.getName())){
            wrapper.like("name",whitelistSetting.getName());
        }
        if(whitelistSetting.getRoleId()!=null){
            wrapper.eq("role_id",whitelistSetting.getRoleId());
        }
        Page<WhitelistSetting> page = new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        baseMapper.selectPage(page, wrapper);
        return page;
    }

    @Override
    public List<StatDTO> stat() {
        return baseMapper.stat();
    }


    public StringBuilder gets(List<WhitelistSetting> users){
        StringBuilder s=new StringBuilder();
        users.stream().forEach(u->s.append(u.getSn()).append(" "));
        return s;
    }

}
